package com.dragon.shop.order.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.dragon.shop.order.service.SentinelService;
import com.dragon.shop.utils.resp.ResponseEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author: Dragon
 * @since: 2023/12/2 8:59
 */
@Slf4j
@RestController
public class SentinelController {

    @Resource
    private SentinelService sentinelService;

    @GetMapping(value = "/request_sentinel1")
    public String requestSentinel1() {
        log.info("测试Sentinel1");
        sentinelService.sendMessage();
        return "Sentinel1";
    }

    @GetMapping(value = "/request_sentinel2")
    public String requestSentinel2() {
        log.info("测试Sentinel2");
        sentinelService.sendMessage();
        return "Sentinel2";
    }

    @GetMapping(value = "/request_sentinel3")
    @SentinelResource("request_sentinel3")
    public ResponseEntity requestSentinel3(String header, String body) {
        try {
            log.info("测试Sentinel3");
            return new ResponseEntity("sentinel3");
        } catch (Exception e) {
            return new ResponseEntity(500, e.getMessage());
        }
    }

    private int count = 0;
    @GetMapping(value = "/request_sentinel4")
    @SentinelResource("request_sentinel4")
    public ResponseEntity requestSentinel4(){
        try {
            log.info("测试Sentinel4");
            count++;
            //模拟异常，比例为50%
            if (count % 2 == 0){
                throw new RuntimeException("演示基于异常比例熔断");
            }
            return new ResponseEntity("Sentinel4");
        } catch (Exception e) {
            return new ResponseEntity(500, e.getMessage());
        }
    }
}
